package com.test.base.buffer;

import lombok.extern.slf4j.Slf4j;

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 基础读取操作
 */
@Slf4j
public class BufferChannelTes1t1 {
    public static void main(String[] args) {
        log.info("BufferChannelTes1t1");
        try (FileChannel channel = new FileInputStream("data.txt").getChannel()) {
            ByteBuffer buffer = ByteBuffer.allocate(10);
            while (true) {
                // 缓存分批读取
                /*
                channel.read在传入的时候读取字符
                 */
                int len = channel.read(buffer);
                log.debug("读取到的字节数：{}", len);

                if (len == -1) {
                    break;
                }

                buffer.flip();
                while (buffer.hasRemaining()) {
                    byte b = buffer.get();
                    log.debug("获取实际字节为：{}", (char) b);
                }
                buffer.clear();
            }
        } catch (IOException e) {
            log.error(e.getMessage());
            e.printStackTrace(System.err);
            throw new RuntimeException(e);
        }
    }
}
